package com.example.comitclx1.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.comitclx1.pojo.Result;
import com.example.comitclx1.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter  implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        HttpServletResponse resp= (HttpServletResponse) servletResponse;
        //请求url
        String url = req.getRequestURL().toString();
        log.info("url{}",url);
        //判断请求是否包含login，如果包含说明登录操作，放行
        if(url.contains("login")){
            log.info("登录");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //获取请求头的令牌（token）
        String jwt = req.getHeader("token");
        log.info(jwt);
        //判断令牌是否存在，不存在返回错误结果
        if(!StringUtils.hasLength(jwt)){
            log.info("不存在");
            Result notLogin = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(notLogin);
            resp.getWriter().write(jsonString);
            return;
        }
        //解析token，如果解析失败，返回错误信息
        try {
            JwtUtils.parseJWT(jwt);
        }catch (Exception e){
            e.printStackTrace();
            log.info("解析失败");
            Result notLogin = Result.error("NOT_LOGIN");
            String jsonString = JSONObject.toJSONString(notLogin);
            resp.getWriter().write(jsonString);
            return;
        }
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
